/**
 * Copyright(c) 2014 Xunton Solutions
 *
 * History:
 *   15-3-24 下午5:13 Created by dwzhang
 */
package com.jade.bss.crm.impl;

import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.jade.bss.base.BssException;
import com.jade.bss.crm.Feedback;
import com.jade.bss.crm.FeedbackDao;
import com.jade.bss.crm.Feedback;
import com.jade.framework.base.criterion.Criteria;
import com.jade.framework.base.criterion.sql.SqlUtils;
import com.jade.framework.base.util.PagingList;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;

/**
 * 采用JPA方式的实现。
 *
 * @author <a href="mailto:dwzhang@xunton.com">dwzhang</a> 
 * @version 1.0 15-3-24 下午5:13
 */
@Named ("bss_feedbackDao")
public class JpaFeedbackDao
        implements FeedbackDao
{
    @PersistenceContext (unitName = "default")
    protected EntityManager entityManager;

    @Caching (evict = {@CacheEvict (value = "bss.feedback.g", key = "#feedback.id"),
            @CacheEvict (value = "bss.feedback.q", allEntries = true)})
    public void addFeedback(Feedback feedback)
            throws BssException
    {
        entityManager.persist(feedback);
    }

    @Caching (evict = {@CacheEvict (value = "bss.feedback.g", key = "#feedback.id"),
            @CacheEvict (value = "bss.feedback.q", allEntries = true)})
    public void updateFeedback(Feedback feedback)
            throws BssException
    {
        entityManager.merge(feedback);
    }

    @Caching (evict = {@CacheEvict (value = "bss.feedback.g", key = "#feedback.id"),
            @CacheEvict (value = "bss.feedback.q", allEntries = true)})
    public void removeFeedback(Feedback feedback)
            throws BssException
    {
        Feedback old = entityManager.find(Feedback.class, feedback.getId());
        if (old != null) {
            entityManager.remove(old);
        }
    }

    @Cacheable (value = "bss.feedback.g", key = "#id")
    public Feedback getFeedback(long id)
    {
        return entityManager.find(Feedback.class, id);
    }

    @Cacheable (value = "bss.feedback.q", key = "#criteria")
    public PagingList<Feedback> queryFeedback(Criteria criteria)
    {
        return SqlUtils.sqlQuery(SQL_SELECT, entityManager, criteria);
    }

    protected static final String SQL_SELECT = "SELECT feedback FROM Feedback feedback";
}
